package com.harmony.rdbstoreexample;
import ohos.app.AbilityContext;
import ohos.data.DatabaseHelper;
import ohos.data.rdb.RdbOpenCallback;
import ohos.data.rdb.RdbStore;
import ohos.data.rdb.StoreConfig;
import ohos.data.resultset.ResultSet;
import ohos.global.resource.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
public class readSqliteFile {
    private AbilityContext context;
    private File dirPath;
    private File dbPath;
    private RdbStore store;
    private StoreConfig config = StoreConfig.newDefaultConfig("PremierLeague.sqlite");
    private static final RdbOpenCallback callback = new RdbOpenCallback() {
        @Override
        public void onCreate(RdbStore rdbStore) {

        }

        @Override
        public void onUpgrade(RdbStore rdbStore, int i, int i1) {

        }
    };
    public readSqliteFile(AbilityContext context)
    {
        this.context = context;
        dirPath = new File(context.getDataDir().toString() + "/MainAbility/databases/db");
        if(!dirPath.exists()){
            dirPath.mkdirs();
        }
        dbPath = new File(Paths.get(dirPath.toString(),"PremierLeague.sqlite").toString());
    }
    private void extractDB() throws IOException{
        Resource resource = context.getResourceManager().getRawFileEntry("resources/rawfile/PremierLeague.sqlite").openRawFile();
        if(dbPath.exists()){
            dbPath.delete();
        }
        FileOutputStream fos = new FileOutputStream(dbPath);
        byte[] buffer = new byte[4096];
        int count = 0;
        while((count = resource.read(buffer)) >= 0){
            fos.write(buffer,0,count);
        }
        resource.close();
        fos.close();
    }
    public void init() throws IOException{
        extractDB();
        DatabaseHelper helper = new DatabaseHelper(context);
        store = helper.getRdbStore(config,1,callback,null);
    }
    public ArrayList<sqliteData> search(){
        ResultSet resultSet = store.querySql("select * from team",null);
        ArrayList<sqliteData> result = new ArrayList<sqliteData>();
        while(resultSet.goToNextRow()){
            sqliteData sqldata = new sqliteData();
            sqldata.no = resultSet.getInt(0);
            sqldata.clubName = resultSet.getString(1);
            result.add(sqldata);
        }
        resultSet.close();
        return result;
    }
}
